import { Notification } from "@arco-design/web-vue";

const preName = location.protocol.includes("https") ? "wss" : "ws";
let time = 0;
const max_time = 1; // 最大连接次数
let timer: any = null; // 计数器
let ws: WebSocket | null = null; // websocket
let isLogin = false; // 用户登录状态
const host = `${preName}://${location.host}`;

// 处理ws消息
const getMessage = (msg: any) => {
  // 过滤pong消息
  const isPong = typeof msg.data === "string" && msg.data.includes("pong");
  if (!isPong) {
    console.log(msg.data);
    // const receivedData = JSON.parse(msg.data); // 包含type的原始数据(起点数据)
    // // 消息
    // if (receivedData.type === "notification") {
    //   Notification.info({
    //     title: "消息",
    //     content: receivedData.msg || "您有一条新的消息",
    //     duration: 10 * 1000,
    //     closable: true,
    //   });
    // }
  }
};

// 初始化websocket
export const initSocket = (token: string) => {
  isLogin = true;
  ws = new WebSocket(`${host}/api/ws?token=${token}`);
  if (time < max_time) {
    // 一旦创建连接立即计数，否则如果连接失败不会计数导致无限重连
    time += 1;
  }

  ws.onopen = () => {
    console.log(`websocket已连接,当前连接次数：${time}次`);
    timer = setInterval(() => {
      ws && ws.send(JSON.stringify({ type: "ping" }));
    }, 30 * 1000);
  };

  ws.onmessage = getMessage;

  ws.onclose = (e) => {
    console.log(e);
    if (isLogin) {
      if (time < max_time) {
        console.log("websocket已关闭，将在5秒后重新连接");
        setTimeout(function () {
          initSocket(localStorage.getItem("token") as string);
        }, 5000);
      } else {
        console.log("websocket已关闭，已超过最大连接次数，自动断开连接");
      }
    }
    clearInterval(timer);
  };
};

// 断开连接
export const closeSocket = () => {
  if (ws) {
    isLogin = false;
    time = 0; // 重置重连计数器
    ws.close();
  }
};
